package com.appspot.niehonglei.action;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.niehonglei.common.Tools;
import com.appspot.niehonglei.dao.PMF;
import com.appspot.niehonglei.jdo.Index;

public class Rss implements ActionInterface {

	@SuppressWarnings("unchecked")
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		try {

			StringBuffer rss = new StringBuffer("");
			rss.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			rss.append("\n<rss xmlns:sns=\"http://www.niehonglei.info/sns\" version=\"2.0\">");
			rss.append("\n\t<channel>");
			rss.append("\n\t\t<title>*Nie's Home*</title>");
			rss.append("\n\t\t<description>追踪技术潮流</description>");
			rss.append("\n\t\t<link>http://www.niehonglei.info/</link>");
			rss.append("\n\t\t<language>zh-cn</language>");
			rss.append("\n\t\t<copyright>Copyright 2010 - 2010 NEHNRE Inc. All Rights Reserved.</copyright>");
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "select from " + Index.class.getName()
					+ " order by createDate desc range 0,10";
			List<Index> list = (List<Index>) pm.newQuery(query).execute();
			for (int i = 0; i < list.size(); i++) {
				rss.append("\n\t\t<item>");
				Index index = list.get(i);
				rss.append("\n\t\t\t<title>" + index.getTitle() + "</title>");
				rss.append("\n\t\t\t<link>http://www.niehonglei.info/detail/"
						+ index.getId() + "</link>");
				rss.append("\n\t\t\t<description><![CDATA["
						+ index.getContent().getValue() + "]]></description>");
				rss.append("\n\t\t\t<author>" + index.getAuthor()
								+ "</author>");
				rss.append("\n\t\t\t<comments>http://www.niehonglei.info/detail/"
								+ index.getId() + "#comment</comments>");
				rss.append("\n\t\t\t<pubDate>" + Tools.date2str(index.getCreateDate())
						+ "</pubDate>");
				rss.append("\n\t\t</item>");
			}
			pm.close();
			rss.append("\n\t</channel>");
			rss.append("\n</rss>");
			response.setContentType("text/xml;charset=UTF-8");
			response.getWriter().print(rss);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
